package grammarLL1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

public class FileGrammarBuilder implements GrammarBuilder {
	private File file;
	
	public FileGrammarBuilder (String filename) throws FileNotFoundException {
		if (filename == null || filename.equals("")) {
			throw new FileNotFoundException("Empty file");
		}
		this.file = new File(filename);
		if (!file.exists()) {
			throw new FileNotFoundException("file: " + filename + " not found");
		}
	}

	@Override
	public List<Production> buildProductions() throws GrammarException {		
		String p = null;
		Production production;
		List<Production> ret = new LinkedList<Production>();
		BufferedReader br = null;
		
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		} catch (FileNotFoundException e1) {
			return null;
		}
		
		try {
			while ((p = br.readLine()) != null) {
				production = new Production(p);
				ret.add(production);
			}
			br.close();
		} catch (IOException e) {
			System.out.println("Error reading grammar file");
		}
		
		return ret;
	}
}
